package com.micro.mic_common.utils;

import lombok.extern.slf4j.Slf4j;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

/**
 * @Description des加解密工具类
 * @Author yijian
 * @Date 2021/12/28 16:47
 **/
@Slf4j
public class DesUtil {

    public final static String DES_KEY="KkV7aiKYrQ3BiwF6SSAFpvsu";

    /**
     * des对称加密
     * @param data
     * @return
     */
    public static String desEncrypt(String data){
        String encryptData = null;
        try{
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY.getBytes());
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(deskey);
            // 加密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
            encryptData=new BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
        }catch (Exception e){
            throw new RuntimeException("des加密异常:",e);
        }
        return encryptData;
    }

    /**
     * des解密数据
     * @param cryptData
     * @return
     */
    public static String desDecrypt(String cryptData){
        String decryptData = null;
        try{
            // DES算法要求有一个可信任的随机数源
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY.getBytes());
            // 创建一个密匙工厂，然后用它把DESKeySpec转换成一个SecretKey对象
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey secretKey = keyFactory.generateSecret(deskey);
            // 解密对象
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
            decryptData=new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(cryptData)));
        }catch (Exception e){
            throw new RuntimeException("des加密异常:",e);
        }
        return decryptData;
    }

    public static void main(String[] args) {

        String ss = "123456";

        String ens = desEncrypt(ss);

        System.out.println(ens);
    }
}
